package org.koyad.portal.misc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.db.PistonDBManager;
import org.koyad.portal.exceptions.FrameworkException;
import org.koyad.portal.utils.LogUtils;

public class PortalPage {
	
	private static final LogUtils LOGGER = LogUtils
			.getLogger(PortalPage.class);
	
	private String pageName = null;
	private String pageId = null;
	private String pageMapping = null;
	private boolean proted = false;
	private String frame = null;
	private boolean internal = false;
	
	public PortalPage(String pageIdORMapping) throws FrameworkException {
		StringBuffer buffer = new StringBuffer();
		buffer.append("SELECT * FROM ");
		buffer.append(FrameworkConstants.TABLE_PAGE);
		buffer.append(" WHERE PAGE_MAPPING = '");
		buffer.append(pageIdORMapping);
		buffer.append("'");
		if(pageIdORMapping.length() == 32) {
			buffer.append(" OR PAGE_ID = '");
			buffer.append(pageIdORMapping);
			buffer.append("'");
		}
		
		LOGGER.info("PAGE SEARCH QUERY ==> " + buffer.toString());
		
		Connection conn = null; 
		Statement stmt = null;
		try {
			conn = PistonDBManager.getConnection();
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(buffer.toString());
			if(rs.next()) {
				pageName = rs.getString("PAGE_NAME");
				pageId = rs.getString("PAGE_ID");
				pageMapping = rs.getString("PAGE_MAPPING");
				if(rs.getString("PROTECTED").equals("Y")) {
					proted = true;
				}
				frame = rs.getString("FRAME");
				if(rs.getString("INTERNAL").equals("Y")) {
					internal = true;
				}
			} else {
//				_pageMapping = "Home";
			}
		} catch (SQLException e) {
			LOGGER.logException(e);
		} finally {
			if(null != stmt) {
				try {
					stmt.close();
				} catch (SQLException e) {
					LOGGER.logException(e);
				}
			}
			if(null != conn) {
				try {
					conn.close();
				} catch (SQLException e) {
					LOGGER.logException(e);
				}
			}
		}
	}
	
	public PortalPage(String _pageName, String _pageId, String _pageMapping, boolean _proted, String _frame, boolean _internal) {
		pageName = _pageName;
		pageId = _pageId;
		pageMapping = _pageMapping;
		proted = _proted;
		frame = _frame;
		internal = _internal;
	}
	
	public String getPageName() {
		return pageName;
	}
	
	public String getPageId() {
		return pageId;
	}

	public String getPageMapping() {
		return pageMapping;
	}
	
	public boolean isProted() {
		return proted;
	}
	
	public String getFrame() {
		return frame;
	}
	
	public boolean isInternal() {
		return internal;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof PortalPage) {
			PortalPage portalPage = (PortalPage)obj;
			return portalPage.getPageId().equals(pageId);
		}
		return false;
	}
	
}
